package front

import (
	"geekai/api/dto/response"
	"geekai/api/handler"
	"geekai/core"
	"geekai/core/types"
	"geekai/model"
	"geekai/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

type OrderHandler struct {
	handler.BaseHandler
}

func NewOrderHandler(app *core.AppServer, db *gorm.DB) *OrderHandler {
	return &OrderHandler{handler.BaseHandler{App: app, DB: db}}
}

// List godoc
// @Summary      订单列表
// @Description  订单列表
// @Tags         前台-订单
// @Accept       json
// @Produce      json
// @Param        page   	 query     int  true  "页码"
// @Param        page_size   query     int  true  "每页数量"
// @Success      200  {object}  types.BizVo{data=response.Page}
// @Router       /api/order/list [get]
// @Security ApiKeyAuth
func (h *OrderHandler) List(c *gin.Context) {
	page := h.GetInt(c, "page", 1)
	pageSize := h.GetInt(c, "page_size", 20)
	userId := h.GetLoginUserId(c)
	session := h.DB.Session(&gorm.Session{}).Where("user_id = ? and status = ?", userId, types.OrderPaidSuccess)
	var total int64
	session.Model(&model.Order{}).Count(&total)
	var items []model.Order
	var list = make([]response.Order, 0)
	offset := (page - 1) * pageSize
	res := session.Order("id desc").Offset(offset).Limit(pageSize).Find(&items)
	if res.Error == nil {
		for _, item := range items {
			var order response.Order
			err := utils.CopyObject(item, &order)
			if err == nil {
				order.Id = item.Id
				order.CreatedAt = item.CreatedAt.Unix()
				order.UpdatedAt = item.UpdatedAt.Unix()
				payMethod, ok := types.PayMethods[item.PayWay]
				if !ok {
					payMethod = item.PayWay
				}
				payName, ok := types.PayNames[item.PayType]
				if !ok {
					payName = item.PayWay
				}
				order.PayMethod = payMethod
				order.PayName = payName
				list = append(list, order)
			} else {
				log.Errorf("拷贝数据出现错误：%v", err)
			}
		}
	}
	utils.SUCCESS(c, response.NewPage(total, page, pageSize, list))
}

// Query godoc
// @Summary      查询订单状态
// @Description  查询订单状态
// @Tags         前台-订单
// @Accept       json
// @Produce      json
// @Param        order_no   	 query     string  true  "订单号"
// @Success      200  {object}  types.BizVo{}
// @Router       /api/order/query [get]
// @Security ApiKeyAuth
func (h *OrderHandler) Query(c *gin.Context) {
	orderNo := h.GetTrim(c, "order_no")
	var order model.Order
	res := h.DB.Where("order_no = ?", orderNo).First(&order)
	if res.Error != nil {
		utils.ERROR(c, "订单不存在！")
		return
	}
	// 判断订单状态是不是支付成功
	if order.Status == types.OrderPaidSuccess {
		utils.SUCCESS(c, gin.H{"status": order.Status})
		return
	}

	counter := 0
	for {
		time.Sleep(time.Second)
		var item model.Order
		h.DB.Where("order_no = ?", orderNo).First(&item)
		if counter >= 15 || item.Status == types.OrderPaidSuccess || item.Status != order.Status {
			order.Status = item.Status
			break
		}
		counter++
	}
	utils.SUCCESS(c, gin.H{"status": order.Status})
}
